package com.example.sbbsec.quartz.util;


import com.example.sbbsec.quartz.entity.Job;
import com.example.sbbsec.quartz.entity.schedule.ScheduleJob;
import com.example.sbbsec.quartz.entity.schedule.cron.CronJob;
import com.example.sbbsec.quartz.entity.schedule.simple.SimpleJob;
import org.quartz.CronScheduleBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.ScheduleBuilder;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;

import static com.example.sbbsec.quartz.util.QuartzConstant.TRIGGER_PREFIX;


/**
 * quartz 工具类
 *
 * @author lowe.yang
 * @date 2019-01-29 09:58
 */
public class QuartzUtil {
    private QuartzUtil() {
    }

    /**
     * 构建任务明细
     *
     * @param job 任务类
     * @return 任务明细
     */
    public static JobDetail buildJobDetail(ScheduleJob job) {
        return JobBuilder
                .newJob(job.getExecutor())
                .withIdentity(job.getJobName(), job.getJobGroup())
                .withDescription(job.getDescription())
                .build();
    }

    /**
     * 构建cron触发器
     *
     * @param job 任务类
     * @return 触发器
     */
    public static Trigger buildCronTrigger(CronJob job) {
        final CronScheduleBuilder builder = CronScheduleBuilder.cronSchedule(job.getCronExpression());

        return buildTrigger(builder, job);
    }

    /**
     * 构建simple触发器
     *
     * @param job 任务类
     * @return 触发器
     */
    public static Trigger buildSimpleTrigger(SimpleJob job) {
        final SimpleScheduleBuilder builder = SimpleScheduleBuilder.simpleSchedule()
                //触发间隔
                .withIntervalInSeconds((int) job.getUnit().toSeconds(job.getInterval()))
                //重复次数
                .withRepeatCount(job.getRepeat());

        return buildTrigger(builder, job);
    }

    /**
     * 构建JobKey
     *
     * @param jobName  任务名称
     * @param jobGroup 任务分组
     * @return JobKey
     */
    public static JobKey buildJobKey(String jobName, String jobGroup) {
        return new JobKey(jobName, jobGroup);
    }

    /**
     * 构建触发器
     *
     * @param scheduleBuilder scheduleBuilder
     * @param job             任务实体
     * @return 触发器
     */
    private static Trigger buildTrigger(ScheduleBuilder scheduleBuilder, Job job) {
        return TriggerBuilder.newTrigger()
                .withIdentity(TRIGGER_PREFIX + job.getJobName(), job.getJobGroup())
                .startNow().withSchedule(scheduleBuilder).build();
    }
}
